package com.handpay.zztong.hp.notification.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.handpay.framework.ClientEngine;
import com.handpay.framework.HttpEngine;
import com.handpay.framework.LuaTableUtil;
import com.handpay.framework.notice.ApiNoticeFactory;
import com.handpay.framework.notice.ApiNoticeListener;
import com.handpay.framework.utils.CommonUtils;
import com.handpay.zztong.hp.R;
import com.handpay.zztong.hp.base.activity.ZZTongActivity;
import com.handpay.zztong.hp.bean.ActionBar;
import com.handpay.zztong.hp.bean.NoticeInfo;
import com.handpay.zztong.hp.bean.ResponseBean;
import com.handpay.zztong.hp.config.ZZTConfig;
import com.handpay.zztong.hp.config.ZZTConstant;
import com.handpay.zztong.hp.db.ormlite.DataBaseModel;
import com.handpay.zztong.hp.log.HPLog;
import com.handpay.zztong.hp.notification.model.NoticeBody;
import com.handpay.zztong.hp.notification.model.UserNoticesBean;
import com.handpay.zztong.hp.protocol.ATProtocolConstant;
import com.handpay.zztong.hp.protocol.BaseProtocolKey;
import com.handpay.zztong.hp.utils.AccountUtils;
import com.handpay.zztong.hp.utils.PreferenceManager;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;

import se.krka.kahlua.vm.LuaTable;

//import com.handpay.zztong.hp.notification.model.UserNotices;

public class NoticeActivity extends ZZTongActivity {

    private MyBaseAdapter mAdapter;
    //    private NoticeDataHelper mNoticeDB;
    private SwipeRefreshLayout mSwipeRefreshWidget;
    private LinearLayoutManager mLayoutManager;
    private RecyclerView mRecyclerView;
    private DataBaseModel dataBaseModel;
    private String userId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_notice);
        super.onCreate(savedInstanceState);
        dataBaseModel =DataBaseModel.getInstance(this);
        userId = AccountUtils.getUserId(this);
        initView();
    }

    private void initView() {
        mSwipeRefreshWidget = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_widget);
        mSwipeRefreshWidget.setColorSchemeColors(getResources().getColor(R.color.colorPrimary));
        //设置刷新监听
        mSwipeRefreshWidget.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                doGetNotices();
            }
        });
        mRecyclerView = (RecyclerView) findViewById(R.id.recycle);
        mRecyclerView.setHasFixedSize(true);

        mLayoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mAdapter = new MyBaseAdapter();
        mAdapter.setData(dataBaseModel.queryNotices(AccountUtils.getUserId(this)));
        mRecyclerView.setAdapter(mAdapter);
    }


    @Override
    public ActionBar getActivityActionBar() {
        ImageView refresh = new ImageView(this);
        refresh.setImageResource(R.drawable.icon_refresh);
        refresh.setPadding(0, 0, 30, 0);
        refresh.setOnClickListener(CommonUtils.createNoQuickResponseViewListener(ZZTConstant.NO_RESPONSE_CLICK_TIME, new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                mSwipeRefreshWidget.setRefreshing(true);
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        doGetNotices();
                    }
                }, 2000);

            }
        }));
        return new ActionBar(getString(R.string.new_notice_title), true, refresh);
    }


    class MyBaseAdapter extends RecyclerView.Adapter<MyBaseAdapter.ItemViewHolder> {
        private List<NoticeBody> noticeInfos = new ArrayList<>();


        private static final int TYPE_ITEM = 0;

        public List<NoticeBody> getList() {
            return noticeInfos;
        }

        MyBaseAdapter() {
        }

        @Override
        public int getItemCount() {

            if (noticeInfos == null) {
                return 0;
            } else {
                return noticeInfos.size();
            }
        }


        @Override
        public int getItemViewType(int position) {

            return TYPE_ITEM;

        }

        /**
         * 界面设置及逻辑处理
         *
         * @param holder   ItemViewHolder
         * @param position 位置
         */
        @Override
        public void onBindViewHolder(final ItemViewHolder holder, final int position) {
            NoticeBody notice = noticeInfos.get(position);
            if (notice.isRead()) {
                holder.itemView.setVisibility(View.INVISIBLE);
            } else {
                holder.itemView.setVisibility(View.VISIBLE);
            }
            if (!TextUtils.isEmpty(notice.getNoticeId())) {
                holder.itemTitle.setText(notice.getTitle());
                holder.itemText.setText(notice.getContent().replaceAll("&", "\n\r"));
                holder.itemTime.setText(CommonUtils.formatYearMMDay(notice.getTime()));
                holder.ll_item.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View v) {
                        NoticeBody info = noticeInfos.get(position);
                        if (info != null) {
                            if (!info.isRead()) {
                                info.setRead(true);
                                dataBaseModel.updateNotice(info);
                                mAdapter.setData(dataBaseModel.queryNotices(userId));
                            }
                            Bundle bundle = new Bundle();
                            bundle.putString("from", "NoticeActivity");
                            ApiNoticeFactory.getInstance().doBroadCastNotice(ApiNoticeListener.NOTICE_ACTION, bundle);
                            Intent intent = new Intent(NoticeActivity.this, NoticeDetailActivity.class);
                            intent.putExtra(NOTICEINFO, info);
                            NoticeActivity.this.startActivity(intent);
                        }
                    }
                });
                holder.ll_item.setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View v) {
                        final NoticeBody info = noticeInfos.get(position);
                        showAlertDialog(NoticeActivity.this, "提示", "是否删除该通知", true, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dataBaseModel.deleteNotice(info);
                                mAdapter.setData(dataBaseModel.queryNotices(userId));
                                dialog.dismiss();
                            }
                        }, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                        return true;
                    }
                });
            }
        }

        /**
         * ViewHolder 的绑定
         *
         * @param parent   parent
         * @param viewType 可以实现多布局
         * @return MyBaseAdapter.ItemViewHolder
         */
        @Override
        public MyBaseAdapter.ItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            ItemViewHolder itemViewHolder;
            View view = null;
            if (viewType == TYPE_ITEM) {
                view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_notice, null);
                view.setLayoutParams(new RecyclerView.LayoutParams(RecyclerView.LayoutParams.MATCH_PARENT, RecyclerView.LayoutParams.WRAP_CONTENT));
            }
            itemViewHolder = new ItemViewHolder(view);
            return itemViewHolder;
        }

        public void setData(List<NoticeBody> mData) {
            this.noticeInfos = mData;
            notifyDataSetChanged();
        }

        /**
         * 正常的Item
         */
        class ItemViewHolder extends RecyclerView.ViewHolder {
            LinearLayout ll_item;
            ImageView itemView;
            TextView itemTitle;
            TextView itemText;
            TextView itemTime;

            ItemViewHolder(View view) {
                super(view);
                ll_item = (LinearLayout) view.findViewById(R.id.ll_item);
                itemView = (ImageView) view.findViewById(R.id.notice_item_newview);
                itemTitle = (TextView) view.findViewById(R.id.notice_item_title);
                itemText = (TextView) view.findViewById(R.id.notice_item_text);
                itemTime = (TextView) view.findViewById(R.id.notice_item_time);
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
//        mAdapter.setData(mNoticeDB.getNoticeLists());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        mNoticeDB.close();
    }


    private void doGetNotices() {
        String userId = AccountUtils.getUserId(this);
        String lastUpdateTime = PreferenceManager.getInstance(this.getApplicationContext()).getString(userId, "");
        Hashtable<String, String> params = new Hashtable<>();
        params.put(BaseProtocolKey.CHANNEL, ClientEngine.CHANNEL);
        params.put(ATProtocolConstant.CLIENTCHANNEL, ZZTConfig.UPDATE_CHANNEL);
        params.put(ATProtocolConstant.UPDATETIME, lastUpdateTime);
        doJsonPost(true, this, ZZTongActivity.Do_GetUserNotices, UserNoticesBean.class, params, false);
    }

    @Override
    public boolean netJsonResponse(String action, ResponseBean resp, boolean showAlert, DialogInterface.OnClickListener on) {
        boolean bResult = super.netJsonResponse(action, resp, showAlert, on);
        if (bResult) {
            return true;
        }
        if (action.equals(ZZTongActivity.Do_GetUserNotices)) {
            mSwipeRefreshWidget.setRefreshing(false);
            UserNoticesBean userNotices = (UserNoticesBean) resp;
            String lastUpdateTime = userNotices.getLastUpdateTime();
            String userId = AccountUtils.getUserId(NoticeActivity.this);
            PreferenceManager.getInstance(NoticeActivity.this.getApplicationContext()).putString(userId, lastUpdateTime);
            if (userNotices.getList() != null && userNotices.getList().size() > 0) {
                for (NoticeBody noticeBody : userNotices.getList()) {
                    noticeBody.setUserId(userId);
                    noticeBody.setLastUpdateTime(lastUpdateTime);
                    dataBaseModel.addNotice(noticeBody);
                }
            }
//            HPLog.d(HPLog.SSX_TAG, "修改更新时间之前:" + dataBaseModel.queryNotices(userId).toString());
//            dataBaseModel.updateLastTime(userId, lastUpdateTime);
//            HPLog.d(HPLog.SSX_TAG, "修改更新时间之后:" + dataBaseModel.queryNotices(userId).toString());
            mAdapter.setData(dataBaseModel.queryNotices(userId));
            mAdapter.notifyDataSetChanged();
        }

        return true;
    }

    @Override
    public boolean netResponse(String action, Hashtable<String, Object> resp, boolean showAlert) {
        if (action.equals(ZZTongActivity.Do_GetUserNotices)) {
            try {
                NoticeActivity.this.closeProgressDialog();
                byte data[] = (byte[]) resp.get(HttpEngine.Key_RespData);
                LuaTable luaTable = LuaTableUtil.stringToLuaTable(data, isDataCompile);
                String items = (String) luaTable.rawget("items");
                String lastUpdateTime = (String) luaTable.rawget("lastUpdateTime");
                List<NoticeInfo> infos = NoticeInfo.getNoticeLists(luaTable, items);
//                    mNoticeDB.checkeNoticeInfos(infos, lastUpdateTime);
//                    mAdapter.setData(mNoticeDB.getNoticeLists());
                HPLog.i("fdl", "成功返回");
            } catch (NumberFormatException e) {
                e.printStackTrace();
            } finally {
                HPLog.i("fdl", "执行最后刷新权限操作");
            }
        }
        return super.netResponse(action, resp, showAlert);
    }


}


